<template>
    <pageTabelLayout>
        <template #pageHeader>
            <div class="search-form isheader" v-if="headerShow">
                <div>
                    <a-form size="small" :model="pageData" layout="inline">
                        <a-form-item label="结算类型" v-if="permissionStore.hasPermisson('jslx.cx1')">
                            <!-- <a-select popup-container="html"  class="bacClass" :style="{ width: '200px' }" :loading="loading" @search="handleSearch"
                            v-model="pageData.dropDownData" :filter-option="false" allow-search allow-clear
                            @focus="focusSel">
                            <a-option v-for="item in pageData.nameList"
                                :value="item.settlementName">{{ item.settlementName }}
                            </a-option>
                        </a-select> -->
                            <a-input allow-clear class="bacClass" placeholder="" v-model="pageData.dropDownData"
                                @press-enter="huiche" />
                        </a-form-item>
                    </a-form>
                </div>
                <div>
                    <Toolbar :items="pageData.btnList" @add="addHandler" @del="deleteHandler" @select="selectHandler"
                        @export="exports" @import="importHandler" @excel="downloadHandler">
                    </Toolbar>
                </div>

            </div>
            <div class="my-divisders">
                <a-divider orientation="center">
                    <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
                    <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
                </a-divider>
            </div>
            <div class="my-tool-bar">
                <!-- '导出', '导入' -->
                <!-- <Toolbar :items="['查询', '新增', '删除']" @add="addHandler" @del="deleteHandler" @select="selectHandler"
                    @export="exports" @import="importHandler" @excel="downloadHandler">
                </Toolbar> -->
            </div>
        </template>
        <template #pageTabel>
            <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height:100%;width: 100%;z-index:999 ;">
                  <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" rowSelection="multiple" @grid-ready="gridReady" style="height:100%"
                    :defaultColDef="defaultColDef" class='ag-theme-alpine' :rowData="table.dataList" :columnDefs="tc"
                    :localeText="localeText1" :getContextMenuItems="getContextMenuItems">
                </AgGridVuesCopys>
            </a-spin>
        </template>
        <paginationCopys :page-size-options="pagingList1" :total="total" show-total show-jumper show-page-size
            @change="PageSize" @page-size-change="change1" style="justify-content: center" :page-size="size"
            :current="page" />
        <a-drawer style="z-index:999" ok-text='保存' cancel-text='关闭' :mask-closable="false"
            :drawer-style="{ 'zIndex': 9999 }" :width="400" :visible="pageData.showAdd" unmountOnClose @ok="sideOk"
            @cancel="pageData.showAdd = false" :ok-loading="pageData.pageLoading">
            <template #title>
                {{ pageData.sideTitle }}
            </template>
            <div>

                <a-form ref="formRef" layout="horizontal" :model="dataForm">
                    <!-- <a-form-item label="编号" field="settlementCode" label-col-flex="80px"
                        :rules="[{ validator: isChiese }, { required: true, message: '编号必填' }]"
                        :validate-trigger="['change', 'blur']">
                        <a-input class="bacClass" placeholder="" v-model="dataForm.settlementCode" @blur="inputBlur" />
                    </a-form-item> -->
                    <a-form-item label="结算类型" field="settlementName" :rules="[{ required: true, message: '结算类型必填' }]"
                        :validate-trigger="['change', 'blur']" label-col-flex="80px">
                        <a-input class="bacClass" placeholder="" v-model="dataForm.settlementName" />
                    </a-form-item>
                    <a-form-item label="扣点" field="point" label-col-flex="80px">
                        <a-input-number class="bacClass" v-model="dataForm.point" :min="0" :max="100" :precision="2"  />
                    </a-form-item>
                    <a-form-item label="备注" field="remark" label-col-flex="80px">
                        <a-textarea class="bacClass" v-model="dataForm.remark" :max-length="400" allow-clear
                            show-word-limit />
                    </a-form-item>
                </a-form>
            </div>
        </a-drawer>
    </pageTabelLayout>
</template>

<script lang="ts">
import { post } from '@/api/http'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table';
import emitter from "@/hooks/useEventBus";
import { ref, reactive, onMounted, toRefs } from 'vue'
import Toolbar from '@/components/Toolbar.vue';
import { Form, Message, Modal } from '@arco-design/web-vue';
import { FormInstance } from '@arco-design/web-vue/es/form';
import { String } from 'lodash';
import { baseURL } from '@/api/axios.config'
import axios from "axios";
import usePermission from '@/store/modules/permission'

import { localeText } from '@/api/aggridZw'
import { pagingList } from '@/api/paging'
import { simplifyMessages } from '@/api/messageSimplification'
interface SettlementType {
    "id": any
    // "settlementCode": string
    "settlementName": string
    "point": string
    "remark": string
}

export default {
    name: "SettlementType",
    setup() {
        const total = ref(0);
        const page = ref(1);
        const size = ref(10);

        const getContextMenuItems = (params: any) => {
            var result = [
                'copy',
            ];
            return result;
        }
        function PageSize(val: any) {
            page.value = val
            doRefresh();
        }

        function change1(val: any) {
            size.value = val
            doRefresh();
        }

        function doRefresh() {
            pageData.pageLoading = true
            post({
                url: "dwPurchase/SettlementType/getPage",
                data: {
                    page: page.value,
                    size: size.value,
                    deleteState: 0,
                    settlementName: pageData.dropDownData
                },
            })
                .then(({ data, code }: any) => {
                    if (code === 200) {
                        table.handleSuccess(data.list);
                        // pagination.setTotalSize(data.total);
                        gridOption.value.setRowData(data.list);
                        total.value = data.total;
                    }
                })
                .catch(console.log).finally(() => {
                    pageData.pageLoading = false
                })
        }

        const { selectedRowKeys, onSelectionChange } = useRowSelection();
        const pagination = usePagination(doRefresh);
        const table = useTable();
        const rowKey = useRowKey("id");
        const tableColumns = useTableColumn([

            {
                title: "序号",
                key: "settlementCode",
                dataIndex: "settlementCode",
                width: 150
            },
            {
                title: "结算类型",
                key: "settlementName",
                dataIndex: "settlementName",
                width: 150
            },
            {
                title: "扣点",
                key: "point",
                dataIndex: "point",
                width: 150
            },
            {
                title: "备注",
                key: "remark",
                dataIndex: "remark",
                width: 150
            },
            {
                title: "创建人",
                key: "createName",
                dataIndex: "createName",
                width: 150
            },
            {
                title: "创建时间",
                key: "createTime",
                dataIndex: "createTime",
                width: 200
            },
            {
                title: "最后修改人",
                key: "updateName",
                dataIndex: "updateName",
                width: 150
            },
            {
                title: "最后修改时间",
                key: "updateTime",
                dataIndex: "updateTime",
                width: 200
            },
            {
                title: '操作',
                key: 'id',
                slotName: 'action',
                width: 150, fixed: 'right'
            }
        ]);

        let tc: any[] = tableColumns.map((o) => {

            let obj = {
                headerName: o.title,
                field: o.key,
                pinned: o['fixed'],
            }
            if (o.slotName === 'action') {
                obj['resizable'] = false
                obj['filter'] = false
                obj['sortable'] = false
                obj["lockPosition"] = "right"
                obj['width'] = 90
                obj['cellRenderer'] = {
                    template: `<a-tag class="tagCss" @click="a" v-if="e">修改</a-tag>`,
                    setup(props: any) {
                        const a = () => {
                            editHandler(props.params.data)
                        }
                        return {
e:pageData.isEdit,
                            a
                        }
                    }

                }
            }

            return obj
        })



        let a = [{
            showRowGroup: 'hide_def',
            "headerName": "",
            "checkboxSelection": true,
            "headerCheckboxSelection": true,
            "pinned": "left",
            "width": 50,
            resizable: false,
            filter: false,
            sortable: false,
            minWidth: 50,
            maxWidth: 50,
            lockPosition: "left",
        }]
        tc = a.concat(tc)

        const pageData = reactive<{
            nameList: [],
            showAdd: boolean,
            sideTitle: string,
            dropDownData: any,
            pageLoading: boolean,
            rHeight: any
            btnList: any[],
            isEdit: boolean
        }>({
            nameList: [],
            showAdd: false,
            sideTitle: '新增产品基础资料',
            dropDownData: "",
            pageLoading: false,
            rHeight: "",
            btnList: [],
            isEdit: false
        });
        //下拉框得到焦点
        const focusSel = () => {
            selCxAll({ settlementName: '' })
        }
        //下拉数据
        const options = ref<any>(pageData.nameList);
        const loading = ref(false);
        const handleSearch = (value: any) => {
            if (value) {
                const ob = { settlementName: value }
                loading.value = true;
                selCxAll(ob);
                options.value = pageData.nameList;
                loading.value = false;
            } else {
                options.value = []
            }
        };

        //下拉框查询
        function selCxAll(val: any) {
            post({
                url: "dwPurchase/SettlementType/getFieldValue",
                data: val
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    console.log(data);
                    // (data as string[]).splice(0, 0, "全部");
                    pageData.nameList = data;

                } else {
                    Message.error({
                        content: "查询失败！",
                        duration: 5000,
                    });
                }
            });
        }

        onMounted(() => {
            doRefresh();
            // 切换tap到本页面执行的方法
            emitter.on("SettlementType", () => {
                doRefresh();
            });

            pageData.rHeight = document.getElementsByClassName("main-section")[0]?.clientHeight
            //表格的高
            if (pageData.rHeight !== undefined) {
                pageData.rHeight = pageData.rHeight - 200;
            }
            window.addEventListener('resize', () => {
                pageData.rHeight = document.getElementById("BaseInfoSetting")?.clientHeight
                //表格的高
                if (pageData.rHeight !== undefined) {
                    pageData.rHeight = pageData.rHeight - 200;
                }

            })
        });
        //查询
        const selectHandler = () => {
            page.value = 1
            doRefresh();
        }
        const queryData = reactive({

            clothType: ""
        });
        const addHandler = () => {
            //清空数据
            for (const key in dataForm) {
                if (key == "id") {
                    dataForm.id = null;
                } else {
                    dataForm[key] = '';
                }
            }
            pageData.showAdd = true
            pageData.sideTitle = '新增结算类型'

        }

        const dataForm = reactive<SettlementType>({
            "id": null,
            // "settlementCode": "",
            "settlementName": "",
            "point": "",
            "remark": ""
        })

        // 表格准备事件
        const gridOption = ref()
        const gridReady = (params: any) => {
            gridOption.value = params.api
        }

        const formRef = ref<FormInstance>()
        const sideOk = () => {
            formRef.value?.validate().then((err) => {
                if (!err) {
                    if (dataForm.point == null || dataForm.point == "") {
                        dataForm.point = '0'
                    }
                    if (pageData.sideTitle === "新增结算类型") {
                        pageData.pageLoading = true
                        dataForm.id = null
                        post({
                            url: "dwPurchase/SettlementType/insert",
                            data: [dataForm],
                        }).then((res: any) => {
                            if (res.code === 200) {
                                formRef.value?.resetFields();
                                pageData.showAdd = false;
                                doRefresh();
                                Message.success({
                                    content: "新增成功",
                                    duration: 5000,
                                });
                            } else {
                                Message.error({
                                    content: res.message,
                                    duration: 5000,
                                });
                            }
                        }).finally(() => {
                            pageData.pageLoading = false
                        })
                    } else {

                        post({
                            url: "dwPurchase/SettlementType/update",
                            data: [dataForm],
                        }).then((res: any) => {
                            if (res.code === 200) {
                                formRef.value?.resetFields();
                                pageData.showAdd = false;
                                doRefresh();
                                //清空数据
                                for (const key in dataForm) {
                                    if (key == "id") {
                                        dataForm.id = null;
                                    } else {
                                        dataForm[key] = '';
                                    }
                                }
                                Message.success({
                                    content: "修改成功",
                                    duration: 5000,
                                });
                            } else {
                                Message.error({
                                    content:simplifyMessages(res.message),
                                    duration: 5000,
                                });
                            }
                        });
                    }
                }
            });
        }
        const deleteHandler = () => {
            // if (selectedRowKeys.value.length === 0) {
            //     return
            // }
            if (gridOption.value.getSelectedRows().length === 0) {
                Message.error('请先勾选');
                return
            }
            Modal.confirm({
                title: '系统提示',
                content: '确认删除选中的数据?',
                onOk() {
                    post({
                        url: 'dwPurchase/SettlementType/delete',
                        // data: selectedRowKeys.value
                        data: gridOption.value.getSelectedRows().map((o: any) => { return o.id })
                    }).then(({ code, data, message }: any) => {
                        if (code === 200) {
                            Message.success({
                                content: '删除成功',
                                duration: 5000
                            })
                            page.value = 1
                            doRefresh()
                        } else {
                            Message.error({
                                content: simplifyMessages(message),
                                duration: 5000
                            })
                        }
                    })
                }
            })
        }
        const editHandler = (record: SettlementType) => {
            dataForm.id = Number(record.id);
            // dataForm.settlementCode = record.settlementCode;
            dataForm.settlementName = record.settlementName;
            dataForm.point = record.point;
            dataForm.remark = record.remark;
            pageData.sideTitle = '修改结算类型'
            pageData.showAdd = true
        };
        //判断是否填写了中文
        const isChiese = (value: string, cb: Function) => {
            return new Promise<void>(resolve => {
                if (window.encodeURI(value).indexOf('%') !== -1) {
                    cb('填写的值不能包含中文！')
                }
                resolve()
            })

        }
        //input离开焦点 将小写转大写
        // const inputBlur = () => {
        //     dataForm.settlementCode = dataForm.settlementCode.toUpperCase();
        // }
        //导出
        const exports = () => {
            // if (selectedRowKeys.value.length === 0) {
            //     Message.error('请先勾选')
            //     return
            // }
            if (gridOption.value.getSelectedRows() === 0) {
                Message.error('请先勾选');
                return
            } else {
                //将表头拼接出来
                let head = "<th>类型编号</th><th>类型名称</th><th>备注</th><th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>"
                //拿到当前表格数据与勾选的行做筛选

                let nowRow = table.dataList.filter(function (o) {
                    return selectedRowKeys.value.indexOf(o["id"]) !== -1;
                })
                let body = "";
                nowRow.forEach(function (o) {
                    body += "<tr><td>" + o["productTypeCode"] + "</td>";
                    body += "<td>" + o["productTypeName"] + "</td>";
                    body += "<td>" + o["remark"] + "</td>";
                    body += "<td>" + o["createName"] + "</td>";
                    body += "<td>" + o["createTime"] + "</td>";
                    body += "<td>" + o["updateName"] + "</td>";
                    body += "<td>" + o["updateTime"] + "</td>";
                    body += "</tr>";
                })
                tableToXlsx(head, '产品类型', body)
                console.log(table)
            }
        }

        function tableToXlsx(head: any, filename: any, body: any) {
            const uri = 'data:application/vnd.ms-excel;base64,',
                template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`;

            const a = document.createElement('a');
            a.href = uri + window.btoa(unescape(encodeURIComponent(template)));
            a.download = filename;
            a.click();
            document.removeChild(a);
        }

        //模板下载
        const downloadHandler = () => {
            window.open(baseURL + 'excel')
        }
        //导入
        const importHandler = () => {

            const inputEle: HTMLInputElement = document.createElement('input')
            inputEle.type = 'file'
            inputEle.id = 'fileUploadExcel'
            inputEle.accept = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
            inputEle.addEventListener('change', (e) => {
                const formData = new FormData()
                if (inputEle.files !== null) {
                    formData.append('file', inputEle.files[0] || '')
                } else {
                    Message.warning('未选择文件！');
                    return
                }
                pageData.pageLoading = true
                axios.post(baseURL + '/product/productType/analyseProductTypeModelModel', formData, {
                    headers: {
                        "Content-Type": 'multipart/form-data',
                        "token": sessionStorage.getItem('USER-TOKEN-KEY')
                    },
                }).then((result) => {
                    if (result.data['code'] === 200) {
                        Message.success('导入成功')
                    } else {
                        Message.error(result.data.message)
                    }

                }).finally(() => {
                    pageData.pageLoading = false
                    doRefresh()
                })
            })
            inputEle.click()
        }
        const headerShow = ref<boolean>(true)
        //设置权限
        // ['查询', '新增', '删除', '导出', '导入']
        const permissionStore = usePermission()

        if (permissionStore.hasPermisson('jslx.cx1')) {

            pageData.btnList.push("查询")
        }
        if (permissionStore.hasPermisson('jslx.xz1')) {
            pageData.btnList.push("新增")
        }
        if (permissionStore.hasPermisson('jslx.sc1')) {
            pageData.btnList.push("删除")
        }
        if (permissionStore.hasPermisson('jslx.xg1')) {
            pageData.isEdit = true
        }
        const handleChange = (_data: any) => {
            table.handleSuccess(_data);
        }
        const defaultColDef = {
            sortable: true,
            resizable: true,
            filter: true,
            // flex: 1
        }
        const localeText1: any = ref(localeText)
        const huiche = () => {
            selectHandler();
        }
        const pagingList1: any = ref(pagingList)
        return {
            permissionStore,
            pagingList1,
            huiche,
            localeText1,
            defaultColDef,
            tc,
            gridOption,
            gridReady,
            total,
            PageSize,
            change1,
            page,
            size,
            deleteHandler,
            sideOk,
            formRef,
            dataForm,
            addHandler,
            selectedRowKeys,
            pagination,
            tableColumns,
            table,
            rowKey,
            pageData,
            queryData,
            editHandler,
            selectHandler,
            // inputBlur,
            isChiese,
            exports,
            options,
            loading,
            handleSearch,
            focusSel,
            downloadHandler,
            importHandler,
            headerShow,
            handleChange,
            getContextMenuItems
        };
    },
    components: { Toolbar,  }
}
</script>
<style scoped lang="less">
:deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
}
</style>